package tech.topcoder.springcloud.simpleweb.service.impl;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import tech.topcoder.springcloud.simpleweb.service.DemoService;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hhj on 17-4-14.
 */
@Service
public class DemoServiceImpl implements DemoService {

    @Resource
    private RestTemplate restTemplate;

    final String SERVICE_HOST = "http://cloud-simple-service";

    @HystrixCommand(fallbackMethod = "fallbackGetList")
    @Override
    public Map<String, Object> getList(int start, int length, String keyword) {
        Map<String, Object> uriVariables = new HashMap<>();
        uriVariables.put("start", start);
        uriVariables.put("length", length);
        uriVariables.put("keyword", keyword);
        return restTemplate.getForObject(SERVICE_HOST + "/demo/list?start={start}&length={length}&keyword={keyword}",
                Map.class, uriVariables);
    }

    private Map<String, Object> fallbackGetList(int start, int length, String keyword) {
        System.out.println("HystrixCommand fallbackMethod handle!");
        Map<String, Object> result = new HashMap<>();
        result.put("total", 0);
        result.put("list", new ArrayList<>());
        return result;
    }
}
